# -*- coding: utf-8 -*-
from flask import current_app

from info import constants
from info import db
from info.models import Category, News, User
from info.utils.common import user_login_data
from info.utils.response_code import RET
from . import user_blue
from flask import render_template, g, redirect, request, jsonify
from info.utils.image_storage import storage

"""查看作者的新闻列表"""


@user_blue.route("/other_news_list")
def other_news_list():
    # 从前端获取新闻分页
    page = request.args.get("p", 1)
    # 获取当前作者的id
    user_id = request.args.get("user_id")
    try:
        page = int(page)
    except Exception as e:
        current_app.logger.error(e)
        page = 1
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
    # 找到当前作者对象
    user = User.query.get(user_id)
    # 获取作者的所有新闻并分页
    paginate = News.query.filter(News.user_id==user.id).paginate(page, constants.OTHER_NEWS_PAGE_MAX_COUNT, False)
    items = paginate.items
    # 当前分页
    current_page = paginate.page
    # 总页数
    total_page = paginate.pages
    other_news_list = []
    for item in items:
        other_news_list.append(item.to_dict())

    data = {
        "news_list": other_news_list,
        "total_page": total_page,
        "current_page": current_page
    }

    return jsonify(errno=RET.OK, errmsg="OK", data=data)


"""作者详情"""


@user_blue.route("/other_info")
@user_login_data
def other_info():
    user = g.user
    if not user:
        return jsonify(errno=RET.PARAMERR, errmsg="请登录")
    # 从前端获取当前新闻的作者id
    other_id = request.args.get("id")
    # 根据当前作者的id查询到作者对象
    try:
        other = User.query.get(other_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="没有查询到该用户")
    if not other:
        return jsonify(errno=RET.PARAMERR, errmsg="未找到作者对象")
    # 如果当前用户已经登陆并且当前新闻有作者
    is_followed = False
    if user and other:
        if other in user.followed:
            is_followed = True
    data = {
        "other_info": other.to_dict(),
        "is_followed": is_followed,
        "user_info": user.to_dict()
    }
    return render_template("news/other.html", data=data)


"""我的关注"""


@user_blue.route("/user_follow")
@user_login_data
def user_follow():
    user = g.user
    if not user:
        return jsonify(errno=RET.PARAMERR, errmsg="请先登陆")
    page = request.args.get("p", 1)
    try:
        page = int(page)
    except Exception as e:
        current_app.logger.error(e)
        page = 1
    # 获取我关注的所有的用户列表并分页展示
    paginate = user.followed.paginate(page, constants.OTHER_NEWS_PAGE_MAX_COUNT, False)
    # 获取关注所有的所有对象
    items = paginate.items
    # 当前业
    current_page = paginate.page
    # 总页数
    total_page = paginate.pages
    # 我关注的用户列表
    follows_list = []
    for item in items:
        follows_list.append(item.to_dict())

    data = {
        "current_page": current_page,
        "total_page": total_page,
        "users": follows_list
    }
    return render_template("news/user_follow.html", data=data)


"""用户新闻列表"""


@user_blue.route("/news_list", methods=["GET", "POST"])
@user_login_data
def news_list():
    user = g.user
    if not user:
        return render_template("/")
    # 从前端获取用户当前新闻
    page = request.args.get("p", 1)
    try:
        page = int(page)
    except Exception as e:
        page = 1
    # 从数据库获取当前用户发表所有的新闻列表
    paginate = News.query.filter(News.user_id == user.id).paginate(page, constants.USER_FOLLOWED_MAX_COUNT, False)
    # 获取所有的新闻对象
    items = paginate.items
    # 获取当前所在业
    current_page = paginate.page
    # 获取总页数
    totle_page = paginate.pages
    # 遍历所有新闻列表
    release_list = []
    for item in items:
        release_list.append(item.to_review_dict())

    data = {
        "current_page": current_page,
        "total_page": totle_page,
        "news_list": release_list
    }

    return render_template("news/user_news_list.html", data=data)


"""新闻发布"""


@user_blue.route("/news_release", methods=["GET", "POST"])
@user_login_data
def news_release():
    user = g.user
    if not user:
        return render_template("/")
    if request.method == "GET":
        # 修改新闻分类，在数据库中找到所有的新闻分类，然后返回给前端
        categorys = Category.query.all()
        # 遍历出所有的新闻类
        category_list = []
        for category in categorys:
            category_list.append(category.to_dict())
        category_list.pop(0)
        data = {
            "categories": category_list
        }

        return render_template("news/user_news_release.html", data=data)
    # 发布新闻是一个表单提交，所以是post请求，把从前端传递的数据提交到数据库的过程
    title = request.form.get("title")  # 新闻标题
    category_id = request.form.get("category_id")  # 新闻分类
    digest = request.form.get("digest")  # 新闻摘要
    index_image = request.files.get("index_image").read()  # 索引图片
    content = request.form.get("content")  # 新闻内容
    source = "个人发布"

    key = storage(index_image)
    # 判断用户发表的新闻内容是否填写完整
    if not all([title, category_id, digest, index_image, content, source]):
        return jsonify(errno=RET.PARAMERR, errmsg="请输入完整参数")
    # 创建新闻对象
    new = News()
    new.title = title
    new.source = source
    new.digest = digest
    new.category_id = category_id
    new.index_image_url = constants.QINIU_DOMIN_PREFIX + key
    new.content = content
    new.status = 1
    new.user_id = user.id

    db.session.add(new)
    db.session.commit()

    return jsonify(errno=RET.OK, errmsg="新闻发布完成")


"""收藏列表"""


@user_blue.route("/collection", methods=["GET", "POST"])
@user_login_data
def collection():
    user = g.user
    if not user:
        return render_template("/")
    # 从前端获取页面，默认从第一页开始
    page = request.args.get("p", 1)
    # 进行判断
    try:
        page = int(page)
    except Exception as e:
        page = 1
    # 获取用户的收藏新闻列表
    paginate = user.collection_news.paginate(page, constants.USER_COLLECTION_MAX_NEWS, False)
    # 获取用户收藏新闻的所有对象
    items = paginate.items
    # 获取当前所在页码
    current_page = paginate.page
    # 获取总页数
    totle_page = paginate.pages
    # 遍历items
    collection_list = []
    for item in items:
        collection_list.append(item.to_review_dict())

    data = {
        "collections": collection_list,
        "current_page": current_page,
        "total_page": totle_page
    }
    return render_template("news/user_collection.html", data=data)


"""修改密码"""


@user_blue.route("/pass_info", methods=["GET", "POST"])
@user_login_data
def pass_info():
    user = g.user
    if not user:
        return redirect("/")
    # 如果是get请求就把基本资料的页面展示出来
    if request.method == "GET":
        data = {
            "user_info": user.to_dict() if user else None
        }
        return render_template("news/user_pass_info.html", data=data)
    # 从前端获取原始密码和新密码，然后对原始密码进行校验，校验成功了才可以修改密码
    old_password = request.json.get("old_password")
    new_password = request.json.get("new_password")
    # 判断原始密码是否正确
    if not user.check_password(old_password):
        return jsonify(errno=RET.PWDERR, errmsg="密码错误")
    # 如果原始密码正确，修改新密码需要把新密码提交到数据库
    user.password = new_password
    db.session.commit()

    return jsonify(errno=RET.OK, errmsg="修改成功")


"""用户头像上传"""


@user_blue.route("/pic_info", methods=["GET", "POST"])
@user_login_data
def pic_info():
    user = g.user
    if not user:
        return redirect("/")
    # 如果是get请求就把基本资料的页面展示出来
    if request.method == "GET":
        data = {
            "user_info": user.to_dict() if user else None
        }
        return render_template("news/user_pic_info.html", data=data)

    # 从前段获取到图片的url地址，然后在七牛云里面找到对应图片，再返回给前端
    avatar = request.files.get("avatar").read()  # 读取它的url地址
    key = storage(avatar)  # 返回一个文件名
    user.avatar_url = key
    db.session.commit()
    data = {
        "avatar_url": constants.QINIU_DOMIN_PREFIX + key
    }
    return jsonify(errno=RET.OK, errmsg="上传成功", data=data)


"""更新个人资料"""


@user_blue.route("/base_info", methods=["GET", "POST"])
@user_login_data
def user_base_info():
    user = g.user
    if not user:
        return redirect("/")
    # 如果是get请求就把基本资料的页面展示出来
    if request.method == "GET":
        data = {
            "user_info": user.to_dict() if user else None
        }
        return render_template("news/user_base_info.html", data=data)

    # 如果是post请求就需要从前端获取用户的基本资料，然后存储到数据库
    signature = request.json.get("signature")
    nick_name = request.json.get("nick_name")
    gender = request.json.get("gender")
    # 判断用户更改基本资料的信息是否填写完整
    if not all([signature, nick_name, gender]):
        return jsonify(errno=RET.PARAMERR, errmsg="请输入完整信息")
    # 把用户的资料更新到数据库
    user.signature = signature
    user.nick_name = nick_name
    user.gender = gender

    db.session.commit()
    return jsonify(errno=RET.OK, errmsg="更改成功")


"""展示个人中心页面"""


@user_blue.route("/info")
@user_login_data
def get_user_info():
    user = g.user
    if not user:
        return redirect("/")
    data = {
        "user_info": user.to_dict() if user else None
    }
    return render_template("news/user.html", data=data)
